package ltd.followkba.page;

import android.view.View;
import android.widget.TextView;

import com.kcbsdk.EventHandler;
import com.kcbsdk.MyManage.AUserFileType;
import com.kcbsdk.MyWorks.AWorksType;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import ltd.advskin.MRAM;
import ltd.advskin.MSKIN;
import ltd.advskin.base.BaseList;
import ltd.advskin.base.BasePage;

import ltd.advskin.base.KcListHolder;
import ltd.advskin.base.KcListListener;
import ltd.advskin.base.KcTwoListener;
import ltd.advskin.base.KcTypeListener;
import ltd.advskin.task.TaskFree;
import ltd.advskin.view.KcBtnImage;
import ltd.advskin.view.KcBtnText;
import ltd.advskin.view.KcHeaderView;
import ltd.advskin.view.KcListView;
import ltd.followkba.MAPP;
import ltd.followkba.MDBS;
import ltd.followkba.R;
import ltd.followkba.comment.MUTIL;
import ltd.followkba.task.App32;
import ltd.followkba.task.App33;
import ltd.followkba.task.App39;
import ltd.followkba.task.BAppUser;
import ltd.followkba.task.BAppWorks;
import ltd.followkba.task.BWorksList;
import ltd.followkba.task.EditUtils;
import ltd.obbphoto.MOBBW;
import main.MAPI;

import static ltd.advskin.MSKIN.MSTRING;
import static ltd.advskin.MSKIN.MTOAST;
import static ltd.advskin.view.KcListView.LIST_PULL_LOAD_MORE;
import static main.MAPI.MSLEEP;
import static main.MAPI.mMyUtils;
import static main.MAPI.mMyWorks;

public class UserHomePage extends BaseList {
    private KcBtnImage kbiHeadWPage;
    private KcBtnText kbtNameWPage;
    private KcBtnText kbtStateWPage;
    private TextView tvUserList;

    private BAppUser mBAppUser;
    private List<BAppWorks> mBAppWorks;
    private KcTwoListener mKcTwoListener;
    private boolean isMyWorks;
    private boolean selectWorks;
    private String gsResult;
    private byte gWorksType;
    private String gsUserIdS;

    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;
    public void MLOG(String text) {
        if (logEnable) {
            MSTRING(MAPI.GET_LOG_NAME(this) + text);
        }
    }

    @Override
    public void onInitView() {                       // 使用者需要继承，初始化页面控件等显示
        setLayout(R.layout.page_user_home);
        if (mBaseInput != null) {                   // 可能仅仅需要刷新，未必是重新开始的
            mBAppUser = mBaseInput.getInput(0);
            selectWorks = mBaseInput.getInput(1);
            mBaseInput = null;                  // 输入参数的使命已经完成，记得及时销毁之
        }
        mKcHeaderView = (KcHeaderView) findViewById(R.id.khvWPage);
        isMyWorks = false;

        if (mBAppUser == null){
            isMyWorks = true;
        }else if (MAPP.mBDbsAccount.WorksType == mBAppUser.WorksType && MAPP.mBDbsAccount.UserIdS.equals(mBAppUser.UserIdS)){
            isMyWorks = true;
        }
        if (isMyWorks){
            gWorksType = MAPP.mBDbsAccount.WorksType;
            gsUserIdS = MAPP.mBDbsAccount.UserIdS;
        }else if (mBAppUser != null){
            gWorksType = mBAppUser.WorksType;
            gsUserIdS = mBAppUser.UserIdS;
        }else {
            MTOAST("用户ID出错");
        }
        String text = String.format("%s的作品 %s", isMyWorks ? "我" : "TA",  MAPP.mWorksName[gWorksType]);
        mKcHeaderView.setTitle(text, new KcTypeListener() {
            @Override
            public void onMessage(int type) {
                switch (type) {
                    case KcHeaderView.TYPE_CLICK_LEFT:
                        onFinish();
                        break;
                }
            }
        });
        kbiHeadWPage = findViewById(R.id.kbiHeadWPage);
        kbtNameWPage = findViewById(R.id.kbtNameWPage);
        kbtStateWPage = findViewById(R.id.kbtStateWPage);
        tvUserList = findViewById(R.id.tvUserList);

        findViewById(R.id.kbtCleanPage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                                       // 刷新
                getAllWorksList(false);
            }
        });

        findViewById(R.id.kbtAllPage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                                       // 全部
                getAllWorksList(true);
            }
        });

        initPageListView( 1 );
        mKcTwoListener = new KcTwoListener() {
            @Override
            public void onMessage(Object object1, Object object2) {  // 刷新下载回来的图片
                int percent = (int)object1;
                if (percent == 102){    // 百分比，-1=view中颜色的选择 0=未选中，1=下载开始 2-101=下载忙 102=下载成功  103=已下载（在列表中不能刷新,否则会循环死机） 104=下载出错
                    setListView(gTabSelect);
                }
            }
        };
//        MLOG(String.format("HomeA A %s %s", gsUserIdS, gWorksType));
    }


    @Override
    public void onInitData(){                                                                       // onInitView结束，开始加载数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (gWorksType == 33 || gWorksType == 49) {
                    App33.setUser(null);
                }
                mBAppUser = MDBS.getBAppUser(gWorksType, gsUserIdS);                                // 注意mBAppUser可能会在线程之中被改变，在UI线程之中使用要先装出来
//mBAppUser=null;
                if (mBAppUser == null) {                                                            // 在数据库没有找到
                    if (gWorksType < 32) {
                        mBAppUser = App32.getUserInfo(gsUserIdS);                                   // 实际找
                        MLOG(String.format("HomeA mApp32A %s %s", gsUserIdS, mBAppUser));
                    }else if (gWorksType == 33 || gWorksType == 49) {
                        mBAppUser = App33.getUserInfo(gsUserIdS);                                   // 实际找
                        MLOG(String.format("HomeA mApp33A %s %s", gsUserIdS, mBAppUser));
                    }else if (gWorksType == 39) {
                        mBAppUser = App39.getUserInfo(gsUserIdS);                                   // 实际找
                    }
                    if (mBAppUser != null) {                                                        // 找到后
                        MDBS.setBAppUser(mBAppUser);
                    }
                }
                if (mBAppUser != null) {
                    if (!MAPI.IS_FILE_DONE(mBAppUser.HeadFile)) {
                        if (gWorksType == 33 || gWorksType == 49) {
                            App33.downloadHeadFile(AUserFileType.IMG_SMALL, mBAppUser, true);
                        }else  if (gWorksType == 39) {
                            EditUtils utils = new EditUtils();
                            utils.downloadPhoto(false, 0, 0, mBAppUser.HeadUrl, mBAppUser.HeadFile);
                        }
                    }
                    getWorksList(false);
                }
                MLOG(String.format("getUserFullInfoAac %s %s %s", gWorksType, gsUserIdS, mBAppUser));
            }
        }).start();

        mMyWorks.setUiEventCallBack(new EventHandler() {
            @Override
            public void onComplete(int methodType, boolean isFail, String message) {
                    if (mMyWorks.isEventDataRefresh()){
                        showInfo();
                        setListView(gTabSelect);
                    }
            }
        });
        if (selectWorks) {
            MSKIN.setText(String.format("点击选择%s作品",  MAPP.mWorksName[gWorksType]), tvUserList);
        }else {
            MSKIN.setText(String.format("%s作品",  MAPP.mWorksName[gWorksType]), tvUserList);
        }
        showInfo();
        setListView(gTabSelect, (List) mBAppWorks);

    }
    @Override
    public void onPageUpdate(BasePage basePage) {    // 更新显示页面数据，用于刷新显示 basePage返回上面的页面，可以使用getPageResult()获得返回的内容
        onInitData();
    }
    @Override
    public void onFinish() {       // 使用者选择性继承，用户按了后退键，不继承就直接关闭了
        setClose();
    }
    private void showInfo() {
        BAppUser bAppUser = mBAppUser;                                                              // 注意mBAppUser可能会在线程之中被改变，所以要先装出来
        if (bAppUser != null) {
            MLOG(String.format("HomeA getUserFullInfoAabB %s(%s)%s", MAPI.GET_FILE_LENGTH(bAppUser.HeadFile), bAppUser.HeadFile, bAppUser.HeadUrl));
            MAPP.showUserHead(bAppUser.HeadFile, bAppUser, kbiHeadWPage);
            MSKIN.setText(bAppUser.UserName, kbtNameWPage);
            MSKIN.setText(MAPP.getUser(bAppUser), kbtStateWPage);
            String text = String.format("点击选择作品(%s)", mBAppWorks != null ? mBAppWorks.size() : 0);
            MSKIN.setText(text, tvUserList);
        }
    }
    private void getAllWorksList(boolean getAll){
        String text = getAll ? "正在准备全部作品" : "正在准备刷新作品";
        MSKIN.setText(text, tvUserList);
        new TaskFree(getAll, new TaskFree.Listener() {
            @Override
            public void onMessage(boolean isThread, Object object) {
                boolean getAll = (boolean)object;
                if (isThread){
                    BAppUser bAppUser = mBAppUser;                                                  // 注意mBAppUser可能会在线程之中被改变，所以要先装出来
                    if (bAppUser != null) {
                        getWorksList(getAll);
                        MDBS.setBAppUser(bAppUser);
                    }
                    return;
                }
                setListView(gTabSelect, (List) mBAppWorks);
                String text = String.format("找到作品%s", mBAppWorks != null ? mBAppWorks.size() : 0);
                MSKIN.setText(text, tvUserList);
            }
        });
    }

    private void getWorksList(boolean getAll){
        BWorksList bWorksList = MDBS.getWorksList(gWorksType, gsUserIdS);
        String[] worksIds = bWorksList != null ? bWorksList.WorksIdS : null;
        MLOG(String.format("HomeA getWorksListA %s %s %s %s", gWorksType, gsUserIdS, worksIds!=null?worksIds.length:0, getAll));
        if (gWorksType == 49) {
            worksIds = null;
        }
        if (getAll || worksIds == null) {           // 需要读取全部或者还没有存在
            if (gWorksType < 32) {
                worksIds = App32.getWorksList(gWorksType, gsUserIdS, getAll);
            } else if (gWorksType == 33) {
                worksIds = App33.getWorksList(gsUserIdS, getAll);    // 实际找
            } else if (gWorksType == 49) {              // 唱吧图片
//MAPI.DELETE_FILE("/storage/emulated/0/FollowKBa/dbs_49/list_287864832.bin");
                BAppWorks[] bAppWorks = (!getAll) ? MDBS.getWorks49List(gsUserIdS) : null;
                MLOG(String.format("HomeA makeWorksList getAll %s %s %s %s", gsUserIdS, getAll, bAppWorks, MDBS.getListPath((byte) 49, gsUserIdS)));

                if (bAppWorks == null) {
                    bAppWorks = App33.getPhotoWorks(gsUserIdS, getAll);
                    MLOG(String.format("HomeA makeWorksList %s %s", gsUserIdS, bAppWorks != null ? bAppWorks.length : 0));
                    if (bAppWorks != null) {
                        for (int index = 0; index < bAppWorks.length; index++) {                    // 找第一张图片作为封面
                            if (bAppWorks[index].Photos != null && bAppWorks[index].Photos.length > 0) {
                                bAppWorks[index].CoverUrl = bAppWorks[index].Photos[0].FileUrl;
                                bAppWorks[index].CoverFile = bAppWorks[index].Photos[0].FileName;
                            }
                            bAppWorks[index].WorksName = MOBBW.autoTitle(bAppWorks[index].Intro);
                            if (bAppWorks[index].WorksName == null) {
                                bAppWorks[index].WorksName = bAppWorks[index].Intro;
                            }
                        }
                        MDBS.setWorks49List(gsUserIdS, bAppWorks);
                    }
                }
                if (bAppWorks != null) {
                    mBAppWorks = Arrays.asList(bAppWorks);
                }
                return;
            } else if (gWorksType == 39){
                worksIds = App39.getWorksList(gsUserIdS, getAll);
            }
            MLOG(String.format("HomeA worksIdS %s %s", gsUserIdS, worksIds!=null?worksIds.length:0));
            if (worksIds != null){
                MDBS.setWorksList(gWorksType, gsUserIdS, worksIds, null);
            }
        }
        if (worksIds != null) {
            mBAppWorks = new ArrayList<>();
            for (int index = 0; index < worksIds.length; index++) {
                String works = worksIds[index];
                BAppWorks bAppWorks = MDBS.getBAppWorks(gWorksType, gsUserIdS, works);
//bAppWorks=null;
                if (bAppWorks != null){
//                    MLOG(String.format("HomeA WORKS_OBB_SONG D %s/%s %s(%s)%s(%s)", index, worksIds.length, bAppWorks.WorksName, bAppWorks.MusicIdS, bAppWorks.LyricUrl, bAppWorks.OriginalUrl));
                    mBAppWorks.add(bAppWorks);
                }else {                             // 没有在记忆之中找到，就需要重新读取了
                    if (gWorksType < 32) {
                        bAppWorks = App32.getWorksInfo(gsUserIdS, works);
                    }else if (gWorksType == 33) {
                        bAppWorks = App33.getWorksInfo(gsUserIdS, works);
                    }else if (gWorksType == 39) {
                        bAppWorks = App39.getWorksInfo(works);
                    }
                    if (bAppWorks != null) {
//                        MLOG(String.format("HomeA WORKS_OBB_SONG E %s(%s)%s(%s)", bAppWorks.WorksName, bAppWorks.MusicIdS, bAppWorks.LyricUrl, bAppWorks.OriginalUrl));
                        bAppWorks.WorksType = (byte) gWorksType;
                        bAppWorks.UserIdS = gsUserIdS;
//                        bAppWorks.Tick = System.currentTimeMillis();
                        MDBS.setBAppWorks(bAppWorks);
                        mBAppWorks.add(bAppWorks);
                    }
                }
            }
        }
    }

    private void selectWorks(View view){
        BAppWorks bAppWorks = (BAppWorks) view.getTag();
        if (bAppWorks != null) {
//            AWorksType aWorksType = mMyUtils.getWorksType(MAPP.mBDbsAccount.WorksType);
//            if (aWorksType == AWorksType.WORKS_OBB_SONG || aWorksType == AWorksType.WORKS_OBB_RECITE){    // 需要伴奏
//                int musicID = MAPI.STRING_DEC32(bAppWorks.MusicIdS);
//                if (musicID < 1){       // 没有伴奏
//                    MTOAST("本作品没有伴奏", 3000);
//                    return;
//                }
//            }

            MDBS.setFreeInt(gWorksType, "WorksType", bAppWorks.WorksType);
            MDBS.setFreeText(gWorksType, "UserIdS", bAppWorks.UserIdS);
            MDBS.setFreeText(gWorksType, "IdS", bAppWorks.WorksIdS);
        }
        setPageResult(bAppWorks);
        setClose();
        MTOAST("已选择作品 "+bAppWorks.WorksName);
    }

    private void deleteWorks(BAppWorks bAppWorks){
        gsResult = null;
        new TaskFree(bAppWorks, new TaskFree.Listener() {
            @Override
            public void onMessage(boolean isThread, Object object) {
                BAppWorks bAppWorks = (BAppWorks)object;
                if (isThread){
//                    App33 app33 = MAPP.mAccount33;
//                    App32 app32 = MAPP.mKcApp32;
                    if (MAPP.mBDbsAccount.WorksType == 33 || MAPP.mBDbsAccount.WorksType == 49) {
                        gsResult = App33.deleteWorks(bAppWorks.UserIdS, bAppWorks.WorksIdS);
                    }else {
                        gsResult = App32.deleteWorks(bAppWorks.UserIdS, bAppWorks.WorksIdS);
                    }
                    return;
                }
                if ("ok".equals(gsResult)) {
                    MTOAST(String.format("已删除作品%s", bAppWorks.WorksName));
                }else {
                    MTOAST(String.format("删除作品出错%s", gsResult));
                }
                setListView(gTabSelect);
            }
        });
    }


    private static final int[] item_works_list = new int[]{
            R.layout.item_works_list, 14,
            R.id.kbiHeadWorks, R.id.kbtNameWorks, R.id.tvArtistWorks, R.id.tvInfoWorks, R.id.kbtDelWorks, R.id.tvStateWorks, R.id.tvIntroWorks,
            R.id.kbtPlayWorks, R.id.kgaWorks, R.id.kbiPhoto0, R.id.kbiPhoto1, R.id.kbiPhoto2, R.id.kbiPhoto3, R.id.kbiPhoto4,
    };
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // KcListView的全部处理，放在页面的最后位置统一处理 ///////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private void initListView(int tab, KcListView kcListView) {
        mKcListView[tab] = kcListView;
        mKcListView[tab].initView(null, item_works_list, null, new KcListListener() {
            @Override
            public int onMessage(int type, int tab, Object object) {
                switch (type) {
                    case LIST_PULL_LOAD_MORE :
                        new TaskFree(null, new TaskFree.Listener() {
                            @Override
                            public void onMessage(boolean isThread, Object object) {
                                if (isThread){
                                }
                            }
                        });
                        showInfo();
                        MLOG(String.format("RecordListPage 更多"));
                        break;
                }
                return 0;
            }
            @Override
            public int onBindItemHolder(boolean skipImage, int tab, int position, final KcListHolder holder) {
                Object object = getListView(tab, position);
                if (object instanceof BAppWorks){
                    BAppWorks bAppWorks = (BAppWorks) object;
//                MLOG(String.format("BAppWorksA %s %s_%04x %08x", position, bAppWorks.MusicID0, bAppWorks.MusicID1, bAppWorks.ClassStyle));
                    if (gWorksType == 33 || gWorksType == 49) {
                        MSKIN.downloadUrlFile(bAppWorks.CoverUrl, bAppWorks.CoverFile, mKcTwoListener);
                    }
                    MAPP.showWorksCover(bAppWorks, bAppWorks.CoverFile, holder.mView[0]);
                    holder.mView[0].setTag(bAppWorks);
                    holder.mView[0].setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            selectWorks(v);
                        }
                    });
                    MAPP.showWorksName(bAppWorks, holder.mView[1]);
                    MSKIN.setText(bAppWorks.ArtistName, holder.mView[2]);
                    String text;
                    if (gWorksType == 33 || gWorksType == 39) {
                        text = "";
                        if (MAPI.isEmpty(bAppWorks.LyricUrl)) {
                            text = "无歌词";
                        }
                        if (gWorksType == 33) {
                            if (MAPI.isEmpty(bAppWorks.OriginalUrl)) {
                                text += " 无原唱";
                            }
                            if (MAPI.isEmpty(bAppWorks.MusicHqUrl) && MAPI.isEmpty(bAppWorks.MusicUrl)) {
                                text += " 无伴奏";
                            }
                        }
                        MSKIN.setText(text, holder.mView[3]);
                    }
                    holder.mView[4].setVisibility(isMyWorks ? View.VISIBLE : View.GONE);            // 删除 kbtDelWorks
                    holder.mView[4].setTag(bAppWorks);
                    holder.mView[4].setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {                                   // 删除
                            BAppWorks bAppWorks = (BAppWorks) v.getTag();
                            deleteWorks(bAppWorks);
                        }
                    });
                    if (bAppWorks.ReleaseDate != 0){
                        text = mMyUtils.getSmartDate(bAppWorks.ReleaseDate);
                    }else {
                        text = MUTIL.SHOW_DATE_FORMAT(2, bAppWorks.CreateTime);
                    }
                    text = String.format("%s %s", text, MAPP.getWorks(bAppWorks));
                    MSKIN.setText(text, holder.mView[5]);
                    MSKIN.setText(bAppWorks.Intro, holder.mView[6]);

//                    if (pvMusicHome != null) {
//                        holder.mView[7].setVisibility(View.VISIBLE);
//                        holder.mView[7].setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//
//                            }
//                        });
//                    }else {
//                        holder.mView[7].setVisibility(View.GONE);
//                    }


                    int length = (bAppWorks.Photos != null) ? bAppWorks.Photos.length : 0;
                    if (length > 0 && gWorksType == 49) {       // 多图片显示
                        holder.mView[8].setVisibility(View.VISIBLE);
                        int line1 = (length > 5) ? 5 : length;
                        int line2 = (length > 5) ? (length-5) : 0;
                        if (line1 > 0) {
                            for (int index = 0; index < line1; index++) {
                                if (MSKIN.downloadUrlFile(bAppWorks.Photos[index].FileUrl, bAppWorks.Photos[index].FileName, mKcTwoListener)){
                                    MSKIN.setBitmap(bAppWorks.Photos[index].FileName, holder.mView[9 + index]);
                                }
                            }
                        }
                        holder.mView[8].setTag(bAppWorks);
                        holder.mView[8].setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (selectWorks) {
                                    selectWorks(v);
                                }
                            }
                        });
                    }else {
                        holder.mView[8].setVisibility(View.GONE);
                    }
                    holder.mItemView.setTag(bAppWorks);
                    holder.mItemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (selectWorks) {
                                selectWorks(v);
                            }
                        }
                    });
                }
                return 0;
            }
        });
        // (d)列表最后更新日期时间 (n)下次更新日期时间 (c)当前数量 (q)列表最大的数量
        mKcListView[tab].setStatus(false, false, "", "", "");
        mKcListView[tab].setTabNumber(tab);
        mKcListView[tab].setSpaceHeight(MRAM.g4ScreenWidth);
    }

    private void initPageListView(int tabQty) {
        mKcListView = new KcListView[tabQty];
        if (tabQty == 1) {
            mKcListView[0] = (KcListView) findViewById(R.id.klvWPage);
            mKcListView[0].setVisibility(View.VISIBLE);
            initListView(0, mKcListView[0]);
            return;
        }
    }
}

